package org.example.snow.demo3;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * @author snowsong
 */
public class RandomNumClient extends Thread {
    @Override
    public void run() {
        // 随机生成数字
        String ip = "0.0.0.0";
        int port = 8886;
        try {
            ServerSocket serverSocket = new ServerSocket();
            InetSocketAddress address = new InetSocketAddress(ip, port);
            // 灵活绑定服务器地址
            serverSocket.bind(address);
            // 监听并接收客户端的连接请求，有阻塞特性，当调用该方法的时候，线程会暂停执行，直到有客户端连接上来
            Socket accept = serverSocket.accept();
            // 获取输入流，读取客户端发送的数据
            OutputStream outputStream = accept.getOutputStream();
            // 包装成打印流，方便写入数据 true 自动刷新缓冲区
            PrintWriter printWriter = new PrintWriter(outputStream, true);
            Random random = new Random();
            // 遍历
            for (int i = 0; i < 10; i++) {
                // 生成随机数
                int num = random.nextInt(10) + 1;
                printWriter.println("随机数：" + num);
                System.out.println("send to flink:" + num);
                // 暂停一秒
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        super.run();
    }
}
